package com.example.demo.dynamic_datasource;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;

/**
 * @Author: HouZeYu
 * @Description:
 * @Date: Created in 21:28 2018/12/29
 */
@Configuration
public class DataSourceConfig {
    @Bean(name = "masterDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.master")
    public DataSource masterDataSource(){
      return DruidDataSourceBuilder.create().build();
    }
    @Bean(name = "slave1DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.slave1")
    public DataSource slave1DataSource(){
        return DruidDataSourceBuilder.create().build();
    }
    @Bean(name = "slave2DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.slave2")
    public DataSource slave2DataSource(){
        return DruidDataSourceBuilder.create().build();
    }
    @Bean(name = "myRoutingDataSource")
    public DataSource myRoutingDataSource( @Qualifier("masterDataSource") DataSource masterDataSource ,
                                           @Qualifier("slave1DataSource") DataSource slave1DataSource,
                                           @Qualifier("slave2DataSource") DataSource slave2DataSource){
        HashMap<Object,Object> targetDataSources = new HashMap<>();
         targetDataSources.put("master",masterDataSource);
         targetDataSources.put("slave_1",slave1DataSource);
         targetDataSources.put("slave_2",slave2DataSource);
         DynamicDataSource dynamicDataSource=new DynamicDataSource();
         dynamicDataSource.setDefaultTargetDataSource(masterDataSource);
         dynamicDataSource.setTargetDataSources(targetDataSources);
         return dynamicDataSource;
    }

}
